// 只使用组件 API时，需要手动导入样式。
import 'element-plus/theme-chalk/el-loading.css'
import { ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading'

let loadingCount = 0
let loading: LoadingInstance

const startLoading = (text: string) => {
  loading = ElLoading.service({
    lock: true,
    text: text || '加载中……',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

const endLoading = () => {
  loading.close()
}

export const showLoading = (text?: string) => {
  if (loadingCount === 0) {
    startLoading(text)
  }
  ++loadingCount
}

export const hideLoading = () => {
  if (loadingCount <= 0) {
    return
  }
  --loadingCount
  if (loadingCount === 0) {
    endLoading()
  }
}
